package com.github.alenfive.examples;

import com.github.alenfive.utils.DataSourceUtils;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;

import java.util.*;

public class NamedParameterJdbcTemplateTest {
    public static NamedParameterJdbcTemplate jdbcTemplate = DataSourceUtils.jdbcTemplate;

    public static void main(String[] args) {

        String sql = "SELECT * FROM api_info WHERE id IN (:ids)";
        Map<String, Object> params = new HashMap();
        params.put("ids", Arrays.asList("0", "1", "2", "3"));
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, params);
        System.out.println(list);

        sql = "SELECT * FROM api_info WHERE id = :ids";
        params = new HashMap();
        params.put("id", "0");
        list = jdbcTemplate.queryForList(sql, params);
        System.out.println(list);
    }

    /**
     * List<User> list = new ArrayList<User>();
     *  list.add(new AppStudent(1,"张三",21));
     *  list.add(new AppStudent(1,"李四",22));
     *  list.add(new AppStudent(1,"王二麻子",23));
     *
     *  SqlParameterSource[] beanSources = SqlParameterSourceUtils.createBatch(list.toArray());
     *  String sql = "INSERT INTO app_student(class_id, name, age) VALUES (:classId, :name, :age)";
     *  namedParameterJdbcTemplate.batchUpdate(sql, beanSources);
     */
    public static void batchInsert() {
        String sql = "INSERT INTO api_example(id, api_info_id) VALUES(:id, :apiInfoId)";
        List<Map<String, Object>> paramList = new ArrayList();
        for (int i = 0; i < 5; i++) {
            Map<String, Object> map = new HashMap() {{
                put("id", UUID.randomUUID().toString());
                put("apiInfoId", UUID.randomUUID().toString());
            }};
            paramList.add(map);
        }
        SqlParameterSource[] beanSources = SqlParameterSourceUtils.createBatch(paramList.toArray());
        jdbcTemplate.batchUpdate(sql, beanSources);
    }
}
